package com.bowen.demo.demo001.CountDownLatch;

import java.util.concurrent.CountDownLatch;

/**
 * <h3>java-study</h3>
 * <p>线程计数器多线程使用</p>
 * @author : zhang.bw
 * @date : 2021-04-28 11:33
 **/
public class CountDownLatchDemo {

	/**
	 * CountDownLatch 的作⽤就是 允许 count 个线程阻塞在⼀个地⽅，直⾄所有线程的任务都执⾏完 毕。
	 * @param args
	 */

	public static void main(String[] args) {
		final CountDownLatch latch = new CountDownLatch(2);
		try {
			new Thread(){
				@Override
				public void run() {
					try {
						System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
						Thread.sleep(3000);
						System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
						latch.countDown();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				};
			}.start();

			new Thread(){
				@Override
				public void run() {
					try {
						System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
						Thread.sleep(3000);
						System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
						latch.countDown();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				};}.start();

			System.out.println("等待 2 个子线程执行完毕...");
			latch.await();
			System.out.println("2 个子线程已经执行完毕");
			System.out.println("继续执行主线程");

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
